//
//  YXYRefreshControl.swift
//  YXYRefreshControl
//
//  Created by 袁向阳 on 16/7/1.
//  Copyright © 2016年 YXY.cn. All rights reserved.
//

import UIKit

let SCREENWIDTH = UIScreen.mainScreen().bounds.size.width
let REFRESHHEIGHT: CGFloat = 50
let NAVBARHEIGHT: CGFloat = 64

/// 判断刷新控件需要走过的偏移量
var ScrollViewOffSet: CGFloat? = 0

// 刷新控件的状态
enum RefreshType : Int{
    case Normal = 0
    case Pulling = 1
    case Refreshing = 2
}

class YXYRefreshControl: UIControl {
    
    // 父控件
    var scroll: UIScrollView?
    // 控件的状态
    var refreshState: RefreshType = .Normal {
        didSet {
            
            switch refreshState {
            case .Normal:
                titleLabel.text = "正常"
                if oldValue == .Refreshing {
                    
                    UIView.animateWithDuration(0.25, animations: { () -> Void in
                        
                        self.scroll?.contentInset.top -= REFRESHHEIGHT
                        
                    })
                }
            case .Pulling:
                titleLabel.text = "下拉中"
            case .Refreshing:
                titleLabel.text = "刷新中"
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    
                    self.scroll?.contentInset.top += REFRESHHEIGHT
                    
                    }, completion: { (_) -> Void in
                        
                        // 发送通知
                        self.sendActionsForControlEvents(UIControlEvents.ValueChanged)
                        
                })
            }
            
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: CGRect(x: 0, y: -REFRESHHEIGHT, width: SCREENWIDTH, height: REFRESHHEIGHT))
        
        setUpUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func layoutSubviews() {
        titleLabel.frame = CGRect(x: 0, y: 0, width: SCREENWIDTH, height: REFRESHHEIGHT)
    }
    
    // 添加子控件
    private func setUpUI () {
        addSubview(titleLabel)
    }
    
    /// 开始刷新
    func startRefreshing () {
        refreshState = .Refreshing
    }
    
    /// 结束刷新
    func endRefreshing () {
        refreshState = .Normal
    }
    
    /// 标题
    lazy var titleLabel: UILabel = {
        let lab = UILabel()
        lab.textColor = UIColor.whiteColor()
        lab.font = UIFont.systemFontOfSize(20)
        lab.textAlignment = .Center
        lab.text = "正常"
        return lab
    }()
    
    
    // MARK: - 移除监察者
    deinit {
        self.scroll!.removeObserver(self, forKeyPath: "contentOffset")
    }
}

extension YXYRefreshControl {
    
    override func willMoveToSuperview(newSuperview: UIView?) {
        
        // 判断父控件是否存在 且 是否是可滚动控件
        guard let scroll = newSuperview as? UIScrollView else {
            return
        }
        self.scroll = scroll
        // KVO监听
        scroll.addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions.New, context: nil)
        
    }
    
    // 观察者实现
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        let viewController = scroll?.getViewController()
        // 如果有控制器 且 控制器有导航条
        if viewController != nil && scroll!.isHaveNavBar(viewController!) {
            ScrollViewOffSet = -NAVBARHEIGHT - REFRESHHEIGHT
        }else {
            ScrollViewOffSet = -REFRESHHEIGHT
        }
        
        // 拖拽状态
        if scroll!.dragging {
            
            if scroll!.contentOffset.y > ScrollViewOffSet && refreshState == .Pulling { // 正常状态，且上一个状态必须是下拉状态，才会赋值
                print("正常")
                refreshState = .Normal
            }else if scroll!.contentOffset.y <= ScrollViewOffSet && refreshState == .Normal { // 下拉状态
                print("下拉")
                refreshState = .Pulling
            }
            
        }else {
            // 松手状态
            if refreshState == .Pulling { // 刷新状态
                
                refreshState = .Refreshing
                
            }
        }
        
        
    }
    
//    private func getViewController () -> UIViewController? {
//        // 判断父控件的控制器是否有导航栏
//        var next = self.scroll!.nextResponder()
//        // 如果是控制器
//        repeat {
//            
//            if ((next?.isKindOfClass(UIViewController.self)) != nil) {
//                return next as? UIViewController
//            }
//            next = next?.nextResponder()
//        }while next != nil
//        
//        return nil
//    }
    
    
}


